package activity;

import enums.CustomActivityStatus;
import enums.CustomActivityType;
import enums.ProductStatus;
import models.BaseModel;
import models.constants.DeletedStatus;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;
import util.common.DateUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.*;

/**
 * Created by liming on 16/7/27.
 * 活动明细
 */
@Entity
@Table(name = "custom_activity_item")
public class CustomActivityItem extends BaseModel {
    public static final String CACHE_CUSTOM_ACTIVITYITEM_BY_CUSTOMACTIVITY_ID = "ULC_CACHE_CUSTOM_ACTIVITYITEM_BY_CUSTOMACTIVITY_ID_";


    /**
     * 活动
     */
    @ManyToOne
    @JoinColumn(name = "custom_activity_id")
    public CustomActivity customActivity;

    /**
     * 产品
     */
    @ManyToOne
    @JoinColumn(name = "product_spec_merchant_id")
    public ProductSpecMerchant productSpecMerchant;

    /**
     * 价格
     */
    @Column(name = "price")
    public Double price;

    /**
     * 活动前价格
     */
    @Column(name = "old_price")
    public Double oldPrice = 0d;

    /**
     * 数量
     */
    @Column(name = "maxNum")
    public Double maxNum;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;

    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 加载参加活动的商品集合
     */
    public static List<CustomActivityItem> loadItemList(long id) {
        return CustomActivityItem.find("customActivity.id=? and customActivity.deletedStatus=? and deleted=?", id, DeletedStatus.UN_DELETED,DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 删除Item
     */
    public static void deleteItem(Integer[] delItemIdArray) {
//        String delIds = UStringUtil.concatStr(",", delItemIdArray);
//        CustomActivityItem.delete("id in (" + delIds + ")");
        String sql = "update custom_activity_item set deleted = ? where id in (" + UStringUtil.concatStr(",", delItemIdArray) + ")";
        em().createNativeQuery(sql).setParameter(1, DeletedStatus.DELETED.getValue()).executeUpdate();
    }
    /**
     * 根据活动 拿到活动商品
     * @param customActivity
     * @return
     */
    public static List<CustomActivityItem> findByCustomActivityId(CustomActivity customActivity) {
        return CustomActivityItem.find("deleted = ? and customActivity = ?" , DeletedStatus.UN_DELETED , customActivity).fetch();
//        return CacheHelper.getCache(CACHE_CUSTOM_ACTIVITYITEM_BY_CUSTOMACTIVITY_ID + customActivity.id, new CacheCallBack<List<CustomActivityItem>>() {
//            @Override
//            public List<CustomActivityItem> loadData() {
//                return CustomActivityItem.find("deleted = ? and customActivity = ?" , DeletedStatus.UN_DELETED , customActivity).fetch();
//            }
//        });
    }

    //判断预售商品是否有预售标识
    public static String checkGoodsIsPreSale(List<CustomActivityItem> ItemList){
        String str="";
        for(CustomActivityItem item:ItemList){
            if(!item.productSpecMerchant.preSale){
                str +=ConvertUtil.toString(item.productSpecMerchant.productSpec.product.name)+ ConvertUtil.toString(item.productSpecMerchant.productSpec.spec)+"," ;
            }
        }
        return str;
    }

    //判断添加的商品是否是上架状态
    public static String checkGoodsIsUp(List<CustomActivityItem> insertItemList){
        String str="";
        for(CustomActivityItem activityItem:insertItemList){
            if(activityItem.productSpecMerchant.productStatus!= ProductStatus.UP){
                str += ConvertUtil.toString(activityItem.productSpecMerchant.productSpec.product.name)+ ConvertUtil.toString(activityItem.productSpecMerchant.productSpec.spec)+"," ;
            }
        }
        return str;
    }
    //根据商户商品Id检索活动商品列表
    public static List<Map<String,Object>> loadByProductSpecMerchantId(Integer[] specMerchantIdArrary){
        String sql="select * from custom_activity_item a " +
                " left join custom_activity b on a.custom_activity_id=b.id " +
                " where (b.custom_activity_type='"+ CustomActivityType.PROMOTION+"' or b.custom_activity_type='"+CustomActivityType.SECKILL+"') " +
                " and( b.custom_activity_status = '"+ CustomActivityStatus.PLAN+"' or b.custom_activity_status='"+CustomActivityStatus.START+"')"+
                " and  a.product_spec_merchant_id in ("+UStringUtil.concatStr(",",specMerchantIdArrary)+")"+
                " and a.deleted="+DeletedStatus.UN_DELETED.getValue()+
                " and b.deleted_status="+DeletedStatus.UN_DELETED.getValue();
        Query query = CustomActivityItem.em().createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }



    /**
     * 根据商品,找到商品参加的活动,活动为未结束状态
     * @param specMerchantId
     */
    public static Boolean countActivityBySpecMerchantId(long specMerchantId,Date beginDate,Date endDate) {

        String sqlSelect="select %s from custom_activity_item a " +
                " left join product_spec_merchants b on a.product_spec_merchant_id=b.id " +
                " left join custom_activity c on a.custom_activity_id=c.id " +
                " where  b.id=%s " +
                " and  a.deleted=%s  " +
                " and c.deleted_status=%s  " +
                " and (c.custom_activity_status='%s' or c.custom_activity_status='%s' ) " +
                " and ((c.begin_date >='%s' and c.begin_date >='%s') or (c.end_date >='%s' and c.end_date >='%s')) " ;
        String sqlCount=String.format(sqlSelect,"count(1)",specMerchantId,DeletedStatus.UN_DELETED.getValue(),DeletedStatus.UN_DELETED.getValue(),CustomActivityStatus.PLAN,CustomActivityStatus.START, DateUtil.dateToString(beginDate,"yyyy-MM-dd"),DateUtil.dateToString(endDate,"yyyy-MM-dd"),DateUtil.dateToString(beginDate,"yyyy-MM-dd"),DateUtil.dateToString(endDate,"yyyy-MM-dd"));
        return ConvertUtil.toLong(CustomActivityItem.em().createNativeQuery(sqlCount).getSingleResult())>0;
    }

}
